<template>
    <div class="divKms">
        <div class="divHeader">
            <div class="divTitle">
                hhu Kms demo
            </div>
            <div class="divActions">
                <ul class="lstTopAcs">
                    <li @click="acInitSettings">init</li>
                    <li @click="acConnectKmsServer">connect</li>
                    <li @click="acLoadChannel">loadChannel</li>
                    <li @click="acLoadSeats">loadSeats</li>
                    <li @click="acCreatePushPeers">create pushers</li>
                    <li @click="acCreatePlayerPeers">create players</li>
                    <li @click="acCloseChannel">close channel</li>
                </ul>
            </div>
            <div class="divUser">
                 
            </div>
        </div>
        <div class="divBody">
            <div class="divLocalVideos">
                <div class="divLocalPeer divVideo"
                    v-for = "(dev,devIndex) in pushers"
                    :key="devIndex"
                >
                    <video :id="'lv-'+dev.deviceId" muted autoplay></video>
                    <div class="divTitle">{{dev.label}}</div>
                    <div class="divAc">
                        <el-button @click="acShareScreen(devIndex)" size="mini" type="primary" style="margin-left:5px"><i class="fa fa-tv"></i></el-button>
                        <el-select v-model="dev.seatCode" size="mini">
                            <el-option
                                v-for="item in seatInfos"
                                :key="item.seatCode"
                                :label="item.seatCode"
                                :value="item.seatCode"
                            >
                            </el-option>    
                        </el-select>      
                        <el-button @click="acOpenPusher(devIndex)" size="mini" type="primary" style="margin-left:5px">open</el-button>
                    </div>
                </div>
            </div>
            <div class="divRemotePeers">
                <div class="divLocalPeer divVideo"
                    v-for = "(player , playerIndex) in players"
                    :key="playerIndex"
                >
                    <video :id="'rv-'+playerIndex" muted autoplay></video>
                    <div class="divTitle"></div>
                    <div class="divAc"> 
                        <el-select v-model="player.seatCode" size="mini">
                            <el-option
                                v-for="item in seatInfos"
                                :key="item.seatCode"
                                :label="item.seatCode"
                                :value="item.seatCode"
                            >
                            </el-option>    
                        </el-select>      
                        <el-button @click="acOpenPlayer(playerIndex)" size="mini" type="success" style="margin-left:5px">open</el-button>
                    </div>
                </div>
            </div> 
        </div>
    </div>
</template>

<script>
    export default {
        mounted(){
            var me = this;
            try{
                me.acInitSettings();
            }
            catch(er){
                console.log(er);
            }
        },
        data(){
            return{
                settings:{
                    channelCode:"kmsChannel",
                    seats:["seat01","seat02","seat03","seat04"],
                    playerCounts:9
                },
                channelInfo:{},
                seatInfos:[],
                seatDict:{},
                devices:[],
                pushers:[],
                players:[],
                msgText:""
            }
        },
        methods:{
            acInitSettings(){
                var me = this;
                try{
                    var players=[]
                    for( var i =0;i<me.settings.playerCounts;i++){
                        players.push({
                            index:i ,
                            peer:null,
                            videoId: 'rv-'+i,
                            seatCode:""
                        });
                    }
                    me.players = players;
                    me.kms.getDevices().then(_dev=>{
                        _dev.videoinput.forEach( item=>{
                            item.seatCode = "";
                        });
                        me.devices = _dev.videoinput;
                        me.pushers = _dev.videoinput.map(dev=>{
                            return {
                                deviceId: dev.deviceId ,
                                label: dev.label,
                                seatCode:""
                            };
                        })
                        me.msgText += "\n"+JSON.stringify(me.devices);
                        console.log(me.devices);
                    })
                }
                catch(er){
                    console.log(er);
                }
            },
            acConnectKmsServer(){
                var me = this;
                try{
                    me.kms.getKmsClient().then(_client=>{
                        return me.kms.getChannels();
                    }).then(_chs=>{
                        me.msgText += "\nconnect to skm svr.";
                        me.msgText += "\n"+JSON.stringify(_chs);
                        console.log('connect to skm svr.');
                        console.log('channels', _chs);
                    });

                }
                catch(er){
                    console.log(er);
                }
            },
            acLoadChannel(){
                var me = this;
                try{
                    me.kms.createChannel(me.settings.channelCode).then(_ch=>{
                        console.log('load channel:',_ch); 
                        me.channelInfo = _ch.data;
                    });
                }
                catch(er){
                    console.log(er);
                }
            },
            acLoadSeats(){
                var me = this;
                try{
                    var index = 0;
                    var seats={};
                    var loadItem = ()=>{
                        if( index< me.settings.seats.length){
                            var seatCode = me.settings.seats[index];
                            me.kms.createSeat( me.settings.channelCode , seatCode).then(_se=>{
                                seats[_se.data.seat.seatCode] = _se.data.seat;
                                if( index<me.pushers.length ){
                                    me.pushers[index].seatCode = seatCode;
                                }
                                index++;
                                loadItem();
                            })
                        }
                        else{
                            me.seatDict = seats;
                            me.seatInfos = Object.values(seats);
                            console.log('load seats.', me.seatInfos);
                        }
                    };
                    loadItem();
                }
                catch(er){
                    console.log(er);
                }
            },
            acCreatePushPeers(){
                var me = this;
                try{
                    var index = 0; 
                    var loadItem = ()=>{
                        if( index< me.pushers.length){
                            var pusher = me.pushers[index];
                            var peerCode = 'pusher_'+pusher.deviceId;
                            var video = document.getElementById('lv-'+pusher.deviceId);
                            me.kms.createKmsPeer(peerCode , 's' , video , me.settings.channelCode , pusher.deviceId).then(_peer=>{
                                pusher.peer = _peer;
                                console.log('create peer:', _peer);
                                index++;
                                loadItem();
                            });
                        }
                        else{ 
                            console.log('load pushers.', me.pushers);
                        }
                    };
                    me.$nextTick().then(_=>{
                        loadItem();
                    });
                }
                catch(er){
                    console.log(er);
                }
            },
            acCreatePlayerPeers(){
                var me = this;
                try{
                    var index = 0; 
                    var loadItem = ()=>{
                        if( index< me.players.length){
                            var player = me.players[index];
                            var peerCode = 'player_'+index;
                            var video = document.getElementById('rv-'+index);
                            me.kms.createKmsPeer(peerCode , 'r' , video , me.settings.channelCode ).then(_peer=>{
                                player.peer = _peer;
                                console.log('create player:', _peer);
                                index++;
                                loadItem();
                            });
                        }
                        else{ 
                            console.log('load players.', me.players);
                        }
                    };
                    me.$nextTick().then(_=>{
                        loadItem();
                    });
                }
                catch(er){
                    console.log(er);
                }
            },
            acCloseChannel(index){
                var me = this;
                try{
                    me.kms.closeChannel(me.settings.channelCode).then(_=>{
                        var url = window.location.origin+  window.location.pathname+"?t="+( new Date()).getTime();
                        window.location.href = url;
                    })
                }
                catch(er){
                    console.log(er);
                }
            },
            acOpenPusher(index){
                var me = this;
                try{
                    console.log( me.pushers, index);
                    var endPoint = me.pushers[index];
                    var seatCode = endPoint.seatCode;
                    var flag = endPoint.seatCode && endPoint.seatCode!=null && 
                        me.seatDict[seatCode] && me.seatDict[seatCode] !=null && me.seatDict[seatCode].id && me.seatDict[seatCode].id!=null && 
                        endPoint.peer && endPoint.peer!=null && endPoint.peer.end && endPoint.peer.end!=null ;
                    if( flag){
                        endPoint.peer.open(seatCode);
                        //me.open(endPoint, seatCode);
                    }
                }
                catch(er){
                    console.log(er);
                }
            },
            acOpenPlayer(index){
                var me = this;
                try{
                    console.log( me.players, index);
                    var endPoint = me.players[index];
                    var seatCode = endPoint.seatCode;
                    var flag = endPoint.seatCode && endPoint.seatCode!=null && 
                        me.seatDict[seatCode] && me.seatDict[seatCode] !=null && me.seatDict[seatCode].id && me.seatDict[seatCode].id!=null && 
                        endPoint.peer && endPoint.peer!=null && endPoint.peer.end && endPoint.peer.end!=null ;
                    if( flag){
                        endPoint.peer.open(seatCode);
                        //me.open(endPoint, seatCode);
                    }
                }
                catch(er){
                    console.log(er);
                }
            },
            acShareScreen(index){
                var me = this;
                try{ 
                }
                catch(er){
                    console.log(er);
                }
            },
            open(endPoint , seatCode){
                var me = this;
                try{
                    console.log( endPoint , seatCode);
                    var peerType = endPoint.peer.peerType;
                    var end = endPoint.peer.end;
                    var ptId = me.seatDict[seatCode].id;
                    me.kms.getKmsClient().then(_client=>{
                        _client.getMediaobjectById( ptId , function(erObj , pt){
                            if( pt && pt!=null){
                                var src = peerType=='s'? end : pt ;
                                var target = peerType=='r'? end : pt ;
                                src.connect( target , function(erConn){
                                    console.log('open media:', src.id,'->', target.id);
                                    console.log( 'open peer.' , erConn&& erConn!=null ? erConn:'success');
                                })
                            }
                        });
                    });
                }
                catch(er){
                    console.log(er);
                }
            }
        }
    }
</script>

<style lang="less" scoped>
    .divKms{
        height: 100%;
    }

    .divHeader{
        position: fixed;
        width: 100%;
        top: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #eee;
        
        .divTitle{
            font-weight: bold;
            font-size: 1.2em;
            padding-left: 15px;
        }

        .divActions{
            padding: 10px;
            ul.lstTopAcs{
                list-style: none;
                display: flex;
                padding: 0;
                margin: 0;
                li{
                    padding: 5px 10px;
                    color: #135ba3;
                }
                li:hover{
                    cursor: pointer;
                    font-weight: bold;
                }
            }
        }
    }

    .divBody{
        height: 100%;
        padding-top: 50px;
        display: flex;

        .divLocalVideos{
            height: 100%;
            width: 20%;
            display: flex;
            flex-direction: column;
            .divVideo{
                height: 25%;
            }
        }
        .divMsg{
            height: 100%;
            width: 20%;;
        }
        .divRemotePeers{
            flex: 1;
            height: 100%;
            display: grid;
            grid-template-rows: 33.333% 33.333% 33.333%;
            grid-template-columns: 33.333% 33.333% 33.333%;
        }
    }

    .divVideo{
        position: relative;
        border: 1px solid #444;
        video{
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
            background-color: #222;
            object-fit: cover;
        }
        .divTitle{
            color: #fff;
            position: absolute;
            left: 10px;
            bottom:10px;
        }
        .divAc{
            position: absolute;
            padding: 5px;
            display: flex;

        }
    }
</style>